package com.example.quartz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.quartz.bean.Result;
import com.example.quartz.bean.entity.QrtzJobDetailsEntity;
import com.example.quartz.bean.entity.QuartzEntity;
import com.example.quartz.service.IJobService;
import com.example.quartz.service.QrtzJobDetailsService;
import lombok.AllArgsConstructor;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("jobService")
@AllArgsConstructor
public class JobServiceImpl implements IJobService {
    private final QrtzJobDetailsService qrtzJobDetailsService;


    @Autowired
    private Scheduler scheduler;

    @Override
    public Result listQuartzEntity(QuartzEntity quartz, Integer pageNo, Integer pageSize) throws SchedulerException {

        int totalCount = qrtzJobDetailsService
                .count(Wrappers.<QrtzJobDetailsEntity>lambdaQuery()
                        .eq(QrtzJobDetailsEntity::getJobName, quartz.getJobName()));

        if (totalCount > 0) {
            Page<QuartzEntity> page = qrtzJobDetailsService.listQuartz(new Page<>(pageNo, pageSize), quartz.getJobName());
            for (QuartzEntity quartzEntity : page.getRecords()) {
                JobKey key = new JobKey(quartzEntity.getJobName(), quartzEntity.getJobGroup());
                JobDetail jobDetail = scheduler.getJobDetail(key);
                quartzEntity.setJobMethodName(jobDetail.getJobDataMap().getString("jobMethodName"));
            }
            return Result.success(page);
        }
        return Result.success();
    }

    @Override
    public Long listQuartzEntity(QuartzEntity quartz) {
        return qrtzJobDetailsService.countQuartz();
    }

    @Override
    @Transactional
    public void save(QuartzEntity quartz) throws Exception {
        //如果是修改  展示旧的 任务
        if (quartz.getOldJobGroup() != null) {
            JobKey key = new JobKey(quartz.getOldJobName(), quartz.getOldJobGroup());
            scheduler.deleteJob(key);
        }
        Class cls = Class.forName(quartz.getJobClassName());
        cls.newInstance();
        //构建job信息
        JobDetail job = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(),
                quartz.getJobGroup())
                .withDescription(quartz.getDescription()).build();
        job.getJobDataMap().put("jobMethodName", quartz.getJobMethodName());
        // 触发时间点
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression());
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger" + quartz.getJobName(), quartz.getJobGroup())
                .startNow().withSchedule(cronScheduleBuilder).build();
        //交由Scheduler安排触发
        scheduler.scheduleJob(job, trigger);
    }
}
